/*
 * * * Compile_AHK SETTINGS BEGIN * * *

[AHK2EXE]
Exe_File=C:\Dropbox\Code Repositories\PM App Launcher (SF-svn)\Include\CWI SB\CWI Search Bar.exe
Created_Date=1
Execution_Level=3
[VERSION]
Resource_Files=C:\Dropbox\Code Repositories\PM App Launcher (SF-svn)\Resource\CSB_icon.ico
Set_Version_Info=1
Company_Name=WSNH Apps
File_Description=Quickly open, index and search objects in CWI from a docked searchbar
File_Version=4.1.0.19
Inc_File_Version=1
Internal_Name=CWI Search Bar.exe
Original_Filename=CWI Search Bar.exe
Product_Name=AutoHotkey_L
Product_Version=1.1.5.3
Set_AHK_Version=1
[ICONS]
Icon_1=C:\Dropbox\Code Repositories\PM App Launcher (SF-svn)\Resource\csb_icon.ico

* * * Compile_AHK SETTINGS END * * *
*/

 
;_____________________________________________________________________
;---------------------------------------------------------------------
;	File: CWI Search Bar
;---------------------------------------------------------------------
;	A simple,  search bar that instantly opens object pages (in the desired
;	view) in CWI. Has many other very useful features such as the ability
;	to quickly "tag" any CWI object with any label the user chooses,
;	and then call that part back up (in any CWI view)
;	by simply typing the label into the search bar. 
;		(see CSB_ScreenShot-View Options.jpg) 
;
;	The bar docks on the desktop and has customizable auto-hide settings 
;	to keep it out of the way.
;
;	(see CSB_ScreenShot-Docked.jpg)
;
;	No more having to wait through a long CWI search, then have to select
;	the correct part and the view that you want to open it in-- working
;	smarter not harder!	
;---------------------------------------------------------------------
 #NoEnv
 #SingleInstance, Force
 SetTitleMatchMode, 2
 SetWorkingDir %A_ScriptDir%
 CoordMode, tooltip, screen
 Functions()
;_____________________________________________________________________
;---------------------------------------------------------------------




;=================================================================
;		TRAY ICON FROM COMPILED RESOURCE
;=================================================================
if a_iscompiled
	menu, tray, icon, %a_scriptfullpath%, -159





;==================================================================
;         			H O T K E Y S 
;==================================================================
hotkey, ifwinactive, CWI Banner 
hotkey, ^enter, add9290
hotkey, ifwinactive, CWI Banner 
hotkey, ^numpadenter, add9290
Hotkey, IfWinActive, CWI Banner
Hotkey, up, getSearchHistory
hotkey, ifwinactive, Microsoft Outlook
Hotkey, F7, searchSelected	
hotkey, ifwinactive
Hotkey, F7, searchSelected	




;=================================================================
;                         HOLD F7 SEARCH MENU
;=================================================================
Menu, searchSelection, Add,   Structure Modify/View - S, selectionMenu
Menu, searchSelection, Add,   Navigate - N, selectionMenu
Menu, searchSelection, Add,   Print - P, selectionMenu
Menu, searchSelection, Add,  Where Used - Wu, selectionMenu
Menu, searchSelection, Add, Sinatures (Promote) - Sig, selectionMenu
Menu, searchSelection, Add, Create/Modify RTA - Mod, selectionMenu
Menu, searchSelection, Color, 5CA7F1


	
	
	
;=================================================================
;                        GOLBAL VARIABLES
;=================================================================
	
	;______________
	; 		GENERAL
	;	
	epub 			= \\corp.halliburton.com\team\WD\Business Development and Technology\General\Engineering Public
	wdpub			= \\corp.halliburton.com\team\WD\Public\Rameen Bakhtiary\PM App Launcher
	userSetINIfName = CWI User Settings.ini        ;User settings INI file name
	links 			= %epub%\pm app logs\strmgmtlks       ;CWI links / Object INI file directory
	plinks 			= %a_workingdir%\Personal Links     ;Personal links directory
	waitTimeClick 	:= 1.25         ;Time [sec] before sending Clicks after CWI window Is active
	waitTimeClose 	:= 1.75       ;Time [sec] before closing Advanced Lookup window after submitting search
	GUIlocked		:= True
	
	
	;________________
	; 		HELP FILE
	;
	helpFile		= %wdpub%\Help Files\files\Include\CWI_SB\Source_Files\CSB_Search_Bar-ahk.html
	
	
	;__________________
	;    Gui parameters
	;
	editWidth		:= 280     ;Edit width    
	sbWidth			:= 50        ;Search Button Width    
	setBtnWidth		:= 50        ;Settings Button Width    
	hlpQutWidth		:= 18        ;? And X Button width
	
	
	
	

;===================================================
;	   		CALCULATE GUI & GUI POSITION
;===================================================
	calcGUI()
	getMonInfo()





;=================================================================
;         Check for calibration & Settings file
;=================================================================
	
	IniRead, sText_y, %A_ScriptDir%\callibrationSettings.ini, fieldCoords, ST, Error
	IniRead, fieldXpos, %A_ScriptDir%\callibrationSettings.ini, fieldCoords, x, Error
	
	;________________________________
	; 		CANT GET Y COORD FROM INI
	;
	if ((sText_y = "Error") || !(sText_y)){
		
		;_______________________________
		; 		CANT GET FROM REG EITHER
		;
		RegRead, sText_y, HKCU, Software\PM App Launcher\CWI Search Bar\fieldCoords, ST		
		If (ErrorLevel || !sText_y)
			noCalib := true			
	}
	
	
	;________________________________
	; 		CANT GET X COORD FROM INI
	;
	if ((fieldXpos = "Error") || !(fieldXpos)){
		
		;_______________________________
		; 		CANT GET FROM REG EITHER
		;
		RegRead, fieldXpos, HKCU, Software\PM App Launcher\CWI Search Bar\fieldCoords, x		
		If (ErrorLevel || !fieldXpos)
			noCalib := true			
	}
	
	
	;_______________________________________________________________________
	; 		COULDNT GET CALLIBRATION DATA -- ASSUME FIRST TIME & GO TO SETUP
	;
	If (noCalib){    
		MsgBox, 4, Welcome!, No calibration file was found...`n`nWould you like to begin setup & calibration now?
		IfMsgBox, No
			ExitApp
		
		;_______________________________________
		; 		RUN CWI SETTINGS AND THEN RETURN
		;
		RunWait, CWI Settings.exe
		sleep 50
		
		IniRead, sText_y, %A_ScriptDir%\callibrationSettings.ini, fieldCoords, ST, Error
		If (ErrorLevel || sText_y="Error")
			ExitApp     ;Closed settings w/o calibrating
		
		Gosub helpTxt   ;Show help Screen
	}
	
	
	;___________________________________________
	; 		CANT FIND THE USER SETTINGS INI FILE
	;
	IfNotExist, %A_ScriptDir%\%userSetINIfName%
	{
		MsgBox Welcome!, please choose the Settings you'd like to use for the CWI Search Bar dock
		
		;__________________________________
		; 		RUN CWI SETTINGS AND RETURN
		;
		RunWait, CWI Settings.exe   ;Run calibration
		sleep 50
		
		IfNotExist, %A_ScriptDir%\%userSetINIfName%
			ExitApp
		
		Gosub helpTxt   ;Show help Screen
	}
	




;=================================================================
;			    Get calibration data from Reg
;=================================================================
	sText_y := RegRead("HKCU", "Software\CWI Search Bar\fieldCoords", "ST")
	Sleep 100
	fieldXpos := RegRead("HKCU", "Software\CWI Search Bar\fieldCoords", "x")
	if (sText_y && !fieldXpos)
		fieldXpos := 295    ;Fix for possible bug where x not written correctly





;=================================================================
;               Read  SETTINGS FROM INI
;=================================================================
	IniRead, tabbedBsing, %userSetINIfName%, CWIsettings, tabBrowsing       
	IniRead, hideWaitTime, %userSetINIfName%, CWIsettings, hideWaitTime
	IniRead, checkFreq, %userSetINIfName%, CWIsettings, checkFreq
	IniRead, showOnRight, %userSetINIfName%, CWIsettings, rightMon
	IniRead, showOnBottom, %userSetINIfName%, CWIsettings, monBottom
	IniRead, custview_rta, %userSetINIfName%, CWIsettings, custView_RTA, m
	IniRead, custview_task, %userSetINIfName%, CWIsettings, custView_Task, sig
	IniRead, custview_part, %userSetINIfName%, CWIsettings, custView_Part, ""






;=================================================================
;			Calculate Gui Options
;=================================================================
	If showOnRight=1    ; Show On Right mon
		xpos:=rightmonc-(guiwidth/2)
	  If (showOnBottom=1){    ; Show On Bottom
		yposMain := bottommon - 20
		yposHidden := Bottommon - 3
	}Else{
		yposMain := 0
		yposHidden := 0
	}
	waitTimeGo := (waitTimeClick*1000)  ; Convert wait Time to MS
	waitTimeCloseIt := (waitTimeClose*1000)    
	If (hideWaitTime>0){                ;Set wait Time to Hide
		hideWaitTime *= 1000
		waitIntervals := (hideWaitTime/250)
	}Else If (hideWaitTime = 0)     ;Instant Hide
		waitIntervals:=0
	Else If (hideWaitTime = -1)    ;Always On Top
		waitIntervals:=-1






;_________________________________________________________________________________________________
;=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
;																BUILD GUI
;
	  
	main:
	ToolTip  ;Remove CWI view tip if showing

	;============
	; Docked Gui
	;============
	If !(GUIlocked){
		Gui, 2:-Caption
		Gui, 2:+Border
		Gui, 2:+AlwaysOnTop
		Gui, 2:+ToolWindow
		Gui, 2:Color, EA31EA
		Gui, 2:Show, NA x%xPos% y%yposHidden% h3 w%guiWidth%, Hidden Banner
		Return
	}
	;============
	; Main Gui
	;============
	If (GUIlocked){
		If (returnFromSearch){     ;Rebuild after a search - dont Set Focus
			returnFromSearch:=False
			mainGuiOptions = NA x%xPos% y%yposmain% h20 w%guiWidth%
			Goto, keepTruckin
		}Else   
			mainGuiOptions = x%xPos% y%yposMain% h20 w%guiWidth%
		
		keepTruckin:
		If (waitIntervals<>-1)      ;Do Not Hide If Set to Never-Hide
			SetTimer, checkIfActive, %checkFreq%

		Gui, 1:-Caption
		Gui, 1:+Border
		Gui, 1:+AlwaysOnTop
		Gui, 1:+ToolWindow
		Gui, 1:Color, 000000

		;Text entry bar
		Gui, 1:Add, Edit, %edit_opts% Y0 h20 hwndSTextHWND vSText gTypeInSearch,
		Gui, 1:Font, S7 w600 CDefault, Veranda
		Gui, 1:Add, Text, x10 y3 +BackGroundTrans, <Enter search Text here>
		
		Gui, 1:Font, s8 w400,
		;'Search' Button
		Gui, 1:Add, Button, %sb_opts% Y0 h20 +Default grunITblank, Search
		
		;'Re-calibrate' Button
		Gui, 1:Add, Button, %setBtn_opts% Y0 h20 gSettings, Settings            
		
		;? And X Buttons
		Gui, 1:Font, S9 CDefault Bold, Veranda
		Gui, 1:Add, Button, %hlp_opts% Y0 h20 ghelptxt, ?
		Gui, 1:Add, Button, %qut_opts% y0 h20 gcloseBanner, X
		
		;Gui Show
		Gui, 1:Show, %mainGuiOptions%, CWI Banner
	}
	Return




;__________________________________ E N D   A U T O - R U N __________________________________
;%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&






;=====================================================================
;			EVENT HANDLE FOR TYPING IN SEARCH - Show popup tooltip
;=====================================================================
	TypeInSearch:
	gui, submit, nohide
	if (instr(%a_guicontrol%, ">")){
		;____________________________________________________
		;  A ">" character was found in last 4 chars of string
		;  show a helper tooltip for the view modestooltip,
		tooltip,
		(LTrim
		View		Option
		-------------------------------
		Navigate		>  n
		Promote		>  sig   (Default for Tasks)
		Print		>  p
		View		>  v
		RTA Modify	>  m   (Default for RTAs)
		Where Used	>  wu
		Modify/View	>  s   (Default for Parts)
		), % xPos, 21
	}else{
		;___________________________________________________________
		;  Turn off tooltip otherwise (in case of erasing the ">")
		ToolTip
	}
	return




;___________________________________________________________________________________________________
;---------------------------------------------------------------------------------------------------





;=================================================================
;                            SUBMIT SEARCH
;=================================================================

	;__________________________________
	; 	CTRL + ENTER SUBMIT - ADD 9290-
	;
	add9290:
	Gui, Submit
	sText := "9290-" sText
	goto beginSearch
	
	
	;________________________________
	; 	REGULAR SUBMIT - BEGIN SEARCH
	;
	runitblank:	
	Gui, Submit
	




;=================================================================
;                             BEGIN SEARCH
;=================================================================
	beginSearch:
	Gui, Destroy
	Tooltip
	SetTimer, checkIfActive, Off
	
	
	;_______________________
	; 	SEARCH TXT:  EMPTY
	;
	If !(SText){
		IfWinExist, Advanced Lookup -
		{   WinActivate, Advanced Lookup -
			Goto, main
		}
		Run, iexplore.exe http://cwiprod.corp.halliburton.com/cwi/AdvLookup.jsp		
		Goto main        
	}

		
	;______________________
	; 	SEARCH TXT:  "qCal"
	;
	If (SText = "qcal"){
		Run, iexplore.exe http://cwiprod.corp.halliburton.com/cwi/AdvLookup.jsp
		WinWaitActive, Advanced Lookup -
		IfWinNotActive, Advanced Lookup -
			WinActivate, Advanced Lookup -
		Sleep, 400
		BlockInput, On
		StatusBarWait,Done,,1,Advanced Lookup -
		Sleep 200
		StatusBarWait,Done,,1,Advanced Lookup -
		Sleep 200
		StatusBarWait,Done,,1,Advanced Lookup -
		Sleep 200        
		qcalLabel:         
		Sleep, 200
		BlockInput, Off
		KeyWait, LButton, d
		MouseGetPos, mx, my
		Sleep, 75
		MsgBox, 35, Write file?, Write calibration file? <No> to try again.
		IfMsgBox, Yes
		{   RegWrite, REG_SZ, HKCU, Software\CWI Search Bar\fieldCoords, x, %mx%
			RegWrite, REG_SZ, HKCU, Software\CWI Search Bar\fieldCoords, ST, %my%
			Sleep, 150
			WinClose, Advanced Lookup -
			Sleep, 150
			Reload
			Goto, main
		}
		IfMsgBox, No
		{   Sleep, 300
			BlockInput, On
			Goto, qcalLabel
		}
		WinClose, Advanced Lookup -
		Sleep, 100
		Goto, main
	}

	
		
	;__________________________________________
	;			 	SEARCH TXT:  ALL OTHERS
	;
	
	
		;==============================
		;	SAVE SEARCH FOR HISTORY
		;==============================
			IniWrite, %stext%, %userSetINIfName%, SearchHistory, lastSearch			
			
			
			
	
		;=====================
		;   Check Personal SCs
		;=====================
			If FileExist(plinks "\" stext ".lnk"){
				Run, %plinks%\%stext%
				Goto, main
			}
		
		
		
		;=====================================================
		;   Check INI FILES
		;
		;	Order:
		;		Get custom URL template
		;		rtaID [rtaids]
		;		rtaID [taskids]
		;		ObjectIDs ini
		;		SAP num INI to get ref num >> Object id ini		
		;=====================================================
		CheckINIfiles:
			;--- IF CUSTOM VIEW - Get custView & trim stext ---
			if RegExMatch(stext, ">(?P<view>\w+)$", cust)
				StringTrimRight, stext, stext, % (StrLen(custview) + 1)


			;--- RTA INI [RTA section] ---
			IniRead, PID, %links%\rtaid.ini, rtaIds, %stext%, Error
			If (pid<>"Error"){
				url := Replace(getURL(custView ? custview : custView_RTA), "[pID]", PID, "All")
				Run, iexplore.exe %url%
				Goto, main
			}
			
			
			;--- RTA INI [TASK section] ---
			IniRead, PID, %links%\rtaid.ini, taskids, %stext%, Error
			If (pid<>"Error"){      
				url := Replace(getURL(custView ? custview : custView_Task), "[pID]", PID, "All")
				Run, iexplore.exe %url%
				Goto, main
			}         
			
			

		   ;--- Object INI ---
			IniRead, PID, %links%\objectids.ini, partids, %stext%, Error
			
			If (pid<>"Error"){      ;Found In part INI
				url := Replace(getURL(custview ? custview : custView_Part), "[pID]", PID, "All")
				Run, iexplore.exe %url%
				Goto, main
			}
			

			;--- Try to get REF num from SAP num ---
			FileRead, sapNumbers, %links%\partSAPnums.ini
			Loop, parse, sapNumbers, `n, `r
			{	
				if RegExMatch(A_LoopField, "i)^(?P<ref>.+)=" stext "$", found){
					IniRead, PID, %links%\objectids.ini, partids, %foundRef%, Error
					If (pid<>"Error"){ 						
						url := Replace(getURL(custview), "[pID]", PID, "All")
						Run, iexplore.exe %url%
						Goto, main
					}
				}
			}
		

		
		;======================
		; Start Normal search
		;======================
		IfWinExist, Advanced Lookup -
		{   ;CWI Advanced Lookup window was found already open
			exist:=True
			Goto, alreadyOpen
		}
		
						
		;Open new ADV Lookup window
		;============================
		Run, iexplore.exe http://cwiprod.corp.halliburton.com/cwi/AdvLookup.jsp
		
		WinActivate, Advanced Lookup -
		WinWaitActive, Advanced Lookup -
		IfWinNotActive, Advanced Lookup -
			WinActivate, Advanced Lookup -
		StatusBarWait,Done,,1,Advanced Lookup -
		Sleep 200
		StatusBarWait,Done,,1,Advanced Lookup -
		Sleep 200
		StatusBarWait,Done,,1,Advanced Lookup -
		Sleep 200
		StatusBarWait,Done,,1,Advanced Lookup -

	alreadyopen:    
		WinActivate, Advanced Lookup -
		IfWinNotActive, Advanced Lookup -
			WinActivate, Advanced Lookup -
		
		Sleep, 400
		BlockInput, On
		Sleep, 150
		WinActivate, Advanced Lookup -
		MouseMove,%fieldXpos%, %sText_y%
		Click 3
		Sleep, 100
		Send, %SText%{Tab}
		Sleep 50
		Send, {Backspace}
		Sleep, 50
		Send, {Enter}
		BlockInput, Off            
		Sleep, %waitTimeCloseIt%
		
		;Abort Search
		;=============
		abortSearch:
		If !exist    ;Dont Close Adv Lookup window that was already open. Might have been a Tab
			If tabbedBsing = 0    ;Dont try to Close Adv Lookup window If tabbed browsing Is used
				WinClose, Advanced Lookup -
		exist:=False
		returnFromSearch:=True
		Goto main
Return







;=================================================================
;                          GET SEARCH HISTORY
;=================================================================
getSearchHistory:
	IniRead, previousSearch, %userSetINIfName%, SearchHistory, lastSearch, 0
	if !previousSearch
		return
	ControlSend,,^a{bs}%previousSearch%, ahk_id %stexthwnd%
return









;=================================================================
;						Get URL format Function
;=================================================================
getURL(custView = ""){
	viewURL := "http://cwiprod.corp.halliburton.com/cwi/" 
	. ((custView = "n" || custView = "nav" || custView = "navigate") ? "Navigate.jsp?id=[pID]"
	: (custView = "sig" || custView = "sigs" || custView = "promote") ? "Navigate.jsp?dir=from&tableID=Approvals%23&id=[pID]"
	: (custView = "wu" || custView = "where used") ? "Navigate.jsp?dir=to&id=[pID]"
	: (custView = "m" || custView = "Mod" || custView = "modify") ? "CreateModifyRta.jsp?id=[pID]"
	: (custView = "v" || custView = "view") ? "View.jsp?dir=to&id=[pID]"
	: (custView = "p" || custView = "print") ? "View_noMenu.jsp?id=[pID]&flowPic=false&printFriendly=True"
	: "StructureManagement.jsp?id=[pID]")
	Return viewURL
}

			
			
			
			
			
			
;===================================================================================================
;	HOTKEY: F7
;---------------------------------------------------------------------------------------------------
;	
;~ #IfWinActive,

searchSelected:
	;~ kdBU:=A_KeyDelay	
	cbBU:=Clipboard
	;~ SetKeyDelay, 20	
	Clipboard=
	Send, ^c
	Sleep 15
	if !Clipboard
		return	
	stext := Trim(Clipboard)

	;_______________________
	; 		CWI CLASS OBJECT
	;
	cwi := new CWI
	pID := cwi.id(stext)
	
	
	
	;==============================================================
	;			Check for hold HK - Show view menu
	;==============================================================
	n:=0
	loop{
		n++
		Sleep, 15
		if n > 10
		{
			Menu, searchSelection, show
			return
		}
		getkeystate, keyVar, F7, P
		IfEqual, keyVar, U, break
	}
	
	
	
	;_________________
	; 		RESTORE CB
	;
	Clipboard := cbBU
	
	
	;______________________________________________
	; 		ID NOT ARCHIVED... GO TO REGULAR SEARCH
	;
	if !pID
		Goto, runitblank
	
Return




selectionMenu:
	if RegExMatch(A_ThisMenuItem, "i).*?\s-\s(\w+)\s*?", view){			
		CWIview := view1
		run, % iexplore.exe cwi.url(stext, CWIview)
	}
return








;=================================================================
;			 Detect Mouse over docked Gui
;=================================================================
;Check If Gui Is active every .25 Seconds (every .15 for instant Hide) 
;And Count how many consecutive checks are inactive. Inactive Time = (Number of times checkIfActive Is called) * .25
;After X Seconds (Set by user), Set the Gui to docked
checkIfActive:
	;Gui Is active, reset timer to 0 
	IfWinActive, CWI Banner    
	{
		waitCounts:=0
		Return
	}
	;Gui Not active
	IfWinNotActive, CWI Banner
	{
		CoordMode, Mouse, Screen                                                                                                                                                                                                                        ;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Bottom mon here
		MouseGetPos, dockedX1, dockedY1
		
		If showonbottom=1
		{
			If (dockedY1<yposmain) Or (dockedx1<xpos) Or (dockedx1>(xpos+guiWidth))     ;Mouse Is Not within Gui area
			{
				waitCount++     ;Add another .25 second If Not active & Mouse isn't hovering
				IfGreater, waitCount, %waitIntervals%       ;Time Limit reached
				{
					SetTimer, checkIfActive, Off
					SetTimer, unHideIt, 150
					GUIlocked:=False
					Gui, 1:Destroy
					Goto, main
				}
				CoordMode, Mouse, Relative
			}
		}
		If showonbottom<>1
		{
			If (dockedY1>19) Or (dockedx1<xpos) Or (dockedx1>(xpos+guiWidth))     ;Mouse Is Not within Gui area
			{
				waitCount++     ;Add another .25 second If Not active & Mouse isn't hovering
				IfGreater, waitCount, %waitIntervals%       ;Time Limit reached
				{
					SetTimer, checkIfActive, Off
					SetTimer, unHideIt, 150
					GUIlocked:=False
					Gui, 1:Destroy
					Goto, main
				}
				CoordMode, Mouse, Relative
			}
		}
	}
Return





;=================================================================
;									Show Normal banner
;=================================================================
unHideIt:
	CoordMode, Mouse, Screen
	MouseGetPos,dockedX,dockedY                                                                                                                                                                                                                        ;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Bottom mon here
	hovertime = 0
	;-----------------Bottom MONITOR
	If (showOnBottom){
		If (dockedY> yposHidden) And (dockedx>xpos) And (dockedx<(xpos+guiWidth)){  ; Mouse Is within docked Gui
			While (dockedY > yposHidden) And (dockedX>xpos) And (dockedx<(xpos+guiWidth)){
				hovertime ++
				Sleep, 15
				MouseGetPos,dockedx,dockedy
				
				;Hovered On dock.... Unhide Gui
				;Doesn't Set as active, so will
				;instantly Hide If Mouse leaves Gui
				;without clicking
				If(hovertime>=10){
					SetTimer, unHideIt, Off
					Gui, 1:Destroy
					Gui, 2:Destroy
					waitCount:=0
					;Run main as Not-docked And Send returnFromSearch
					;option which doesn't activate Gui
					returnFromSearch:=True
					GUIlocked:=True
					;~ waitCount:=0
					Goto, main
				}
			}
		}
	}
	If (showonbottom<>1){
		
		If (dockedY<5) And (dockedx>xpos) And (dockedx<(xpos+guiWidth)){  ; Mouse Is within docked Gui
			While (dockedY<5) And (dockedX>xpos) And (dockedx<(xpos+guiWidth)){
				hovertime ++
				Sleep, 15
				MouseGetPos,dockedx,dockedy
				
				;Hovered On dock.... Unhide Gui
				;Doesn't Set as active, so will
				;instantly Hide If Mouse leaves Gui
				;without clicking
				If(hovertime>=10){
					SetTimer, unHideIt, Off
					Gui, 1:Destroy
					Gui, 2:Destroy
					waitCount:=0
					;Run main as Not-docked And Send returnFromSearch
					;option which doesn't activate Gui
					returnFromSearch:=True
					GUIlocked:=True
					;~ waitCount:=0
					Goto, main
				}
			}
		}  
	}
Return





;=================================================================
;									Close Button
;=================================================================
closeBanner:
	ExitApp
Return






;=================================================================
;									Help Button
;=================================================================
helpTxt:
	If FileExist(helpFile){	;Run helpFile
		run, % helpFile
		return
	}
	
	If FileExist(A_ScriptDir "\..\..\Resource\CSB_help.txt"){
		FileRead, helpMsgTxt, %A_ScriptDir%\..\..\Resource\CSB_help.txt
		SplashImage, ,  m2 CX0 W650, , %helpmsgtxt%,
	}else{
		msgbox, 4144, CWI Search Bar, `nSorry... The help file could not be located...
		return
	}
Return






;=================================================================
;									Settings Button
;=================================================================
Settings:
	SetTimer, checkIfActive, Off
	SetTimer, unHideIt, Off
	Gui, 1:Destroy
	Gui, 2:Destroy
	RunWait, CWI Settings.exe
	Sleep, 200
	Reload    
Return





;=================================================================
;									Hide ToolTip
;=================================================================
TToff:
	SetTimer, TToff, Off
	ToolTip
Return





;=================================================================
;									Personal SC Manager
;=================================================================
#IfWinActive, CWI Banner
^f9::goto, personalscManage






;=================================================================
;	Function: getMonInfo
;		Get monitor info to use in centering and displaying GUI
;
;	Returns:
;		None. Sets global variable *xPos* to the required x position
;		of the GUI in order to center it in the left monitor.
;=================================================================
getMonInfo(){
	global
	SysGet, numMons, MonitorCount
	SysGet, leftMon1, Monitor, 1  
	leftMon := leftMon1Right    ; Size of Left monitor
	bottomMon := leftmon1bottom     ;Bottom of monitor
	If (numMons>1){     ;Detected multiple monitors (assume 2)
		SysGet, totalMon, Monitor, 2    ; totalMonRight = total (combined) size of monitors
		rightMon := totalMonRight - leftMon      ;Size of Right monitor
		If (rightMon < 0){    ;Left And Right monitors are reverse referenced as 2 And 1
			leftMon:=leftMon+rightMon
			rightMon:=rightmon*-1
		}
	}
	rightMonC := leftMon + (rightMon/2)      ;Center of Right monitor
	leftMonC := leftMon / 2        ;Center of Left monitor
	xPos := round(leftMonC - (guiWidth/2))      ; Gui Top left.  Centered to Left monitor
}






;=================================================================
;           PERFORM CALCULATIONS ON VAR INPUTS TO BUILD GUI
;=================================================================
calcGUI(){
	global
	sb_x:=editWidth+1
	setBtn_x:=sb_x+sbWidth
	hlp_x:=setBtn_x+setBtnWidth
	qut_x:=hlp_x+hlpQutWidth    
	edit_opts = x0 w%editWidth%
	sb_opts = x%sb_x% w%sbWidth%
	setBtn_opts = x%setBtn_x% w%setBtnWidth%
	hlp_opts = x%hlp_x% w%hlpQutWidth%
	qut_opts = x%qut_x% w%hlpQutWidth%  
	guiWidth:= qut_x+hlpQutWidth
}




;==============================================================
;	Group: About
;		General script file information
;
;		- *Written By:* 	Rameen Bakhtiary
;		- *Last Modified:*	11/12/2011
;==============================================================



;________________________________  I N C L U D E   F I L E S  _____________________________________
;-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#Include CSB_personalSCmanage.ahk
#Include %A_ScriptDir%\..\..\CWI Functions\oCWI.ahk
